package com.system.util;

import com.system.entity.Permission;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname FileUtil
 * @Date 2023/6/1 10:59
 * @Created ZFC
 */
public class FileUtil {


    /**
     * 通过上传权限模板，解析工作簿数据
     * @param sheet
     * @return
     */
    public static List<Permission> parseUploadSheetPermissionTemplate(Sheet sheet) {
        //首行下标
        int firstRowNum = sheet.getFirstRowNum();
        // 尾行下标
        int lastRowNum = sheet.getLastRowNum();

        // 获取表头行
        Row row = sheet.getRow(firstRowNum);

        //获取第一个单元格编号
        int firstCellNum = row.getFirstCellNum();
        //获取最后一个单元格编号
        int lastCellNum = row.getLastCellNum();

        List<Permission> list = new ArrayList<>();

        //第三行开始就是权限数据了
        for (int i = firstRowNum + 2; i <= lastRowNum; i++) {
            //获取当前行
            Row sheetRow = sheet.getRow(i);
            Permission permission = new Permission();
            for (int j = firstCellNum; j < lastCellNum; j++) {
                //获取当前单元格
                Cell cell = sheetRow.getCell(j);
                //设置单元格类型为String
                cell.setCellType(Cell.CELL_TYPE_STRING);
                //获取当前单元格的下标
                switch (cell.getColumnIndex()) {
                    case 0:
                        permission.setPermissionKey(cell.getStringCellValue().trim());
                        break;
                    case 1:
                        permission.setPermissionSort(Integer.valueOf(cell.getStringCellValue().trim()));
                        break;
                    case 2:
                        permission.setRemark(cell.getStringCellValue().trim());
                        break;
                }
            }
            list.add(permission);
        }

        return list;
    }

    /**
     * 解析前端传过来的文件，获取工作簿数据
     *
     * @param file
     * @return
     */
    public static Sheet parseFileGetSheetData(MultipartFile file) throws IOException {

        //1、解析文件
        InputStream inputStream = file.getInputStream();
        //2、获取文件名称
        String fileName = file.getOriginalFilename().trim().toLowerCase();

        Workbook book;
        if (fileName.endsWith(".xlsx")) {
            //通过流的方式读取文件
            book = new XSSFWorkbook(inputStream);
        } else if (fileName.endsWith(".xls")) {
            POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
            //通过流的方式读取文件
            book = new HSSFWorkbook(poifsFileSystem);
        } else {
            return null;
        }
        inputStream.close();
        return book.getSheetAt(0);
    }

    /**
     * 下载批量添加的模板
     *
     * @param templateName 模板名
     * @param request
     * @param response
     * @throws IOException
     */
    public static void downLoadBatchAddTemplate(String templateName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1、根据下载相对目录获取下载目录在服务器部署之后绝对目录
        ClassPathResource classPathResource = new ClassPathResource("/static/fileTemplates/" + templateName);

        // 2. 通过文件输入流读取文件
        InputStream inputStream = classPathResource.getInputStream();

        // 3. 获取响应输出流
        response.setContentType("text/plain;charset=UTF-8");

        // 4. 附件下载 attachment 附件 inline 在线打开(默认值)
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(templateName, "UTF-8"));

        // 5. 处理下载流复制
        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] b = new byte[1024];
        while (len != -1) {
            len = inputStream.read(b);
            outputStream.write(b, 0, len);
        }
        //释放资源
        outputStream.close();
        inputStream.close();
    }

}
